import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wkweb/entities/article_list.dart';
import 'package:wkweb/entities/wk_response.dart';
import 'package:wkweb/net/http_manager.dart';
import 'package:wkweb/util/route_paths.dart';
import 'package:wkweb/util/utils.dart';
import 'package:wkweb/view/list_page_widgets.dart';
import 'package:wkweb/view/state_layout.dart';

class WkRefreshedList extends StatefulWidget {
  final String Function(int page)? getRequestUrl;
  final bool methodGet;
  final Object? params;

  const WkRefreshedList(
      {required this.getRequestUrl,
      required this.methodGet,
      this.params,
      Key? key})
      : super(key: key);

  @override
  _WkRefreshedListState createState() => _WkRefreshedListState();
}

class _WkRefreshedListState extends State<WkRefreshedList> {
  RefreshController? _refreshController;
  var utils = Utils();
  int _loadState = StateLayout.stateLoading;
  List<Datas> _listData = <Datas>[];

  int _currentPage = 0;
  bool showFloat = false;
  bool loadItems = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _refreshController = RefreshController();

    _loadList(0);
  }

  @override
  Widget build(BuildContext context) {
    return StateLayout(
        successWidget: SmartRefresher(
          controller: _refreshController!,
          enablePullUp: true,
          onRefresh: () => _refreshList(),
          onLoading: () => _loadMore(),
          child: ListView.builder(
              physics: BouncingScrollPhysics(),
              itemBuilder: (BuildContext context, int index) {
                return InkWell(
                    onTap: () => _listItemClick(_listData[index]),
                    child: ListItem(_listData[index]));
              },
              itemExtent: 100,
              itemCount: _listData.length),
        ),
        state: _loadState);
  }

  ///列表点击跳转
  _listItemClick(Datas data) {
    Navigator.of(context)
        .pushNamed(RoutePaths.pathWebPage, arguments: data.link ?? "");
  }

  ///刷新
  _refreshList() {
    _loadList(0);
    setState(() {
      _currentPage = 0;
    });
  }

  /// 加载更多
  _loadMore() {
    int addedPage = _currentPage + 1;
    _loadList(addedPage);
    setState(() {
      _currentPage = addedPage;
    });
  }

  ///加载文章列表 ，参数：页码
  _loadList(int page) {
    String url = widget.getRequestUrl!(page);
    if (widget.methodGet) {
      HttpManager.getData(url,
          success: (result) => _loadSuccess(page, result),
          fail: (e) => _loadFail(page, e));
    } else {
      HttpManager.postData(url,
          params: widget.params,
          success: (result) => _loadSuccess(page, result),
          fail: (e) => _loadFail(page, e));
    }
  }

  _loadSuccess(int page, result) {
    WkResp resp = WkResp.fromJson(result);
    List<Datas> articleList =
        ArticleList.fromJson(resp.data).datas ?? List.empty();
    List<Datas> dl = List.empty(growable: true);
    if (page > 0) {
      //加载更多
      dl.addAll(_listData);
    }
    dl.addAll(articleList);
    setState(() {
      _listData = dl;
      _loadState = StateLayout.stateSuccess;
    });
    if (page > 0) {
      _refreshController?.loadComplete();
    } else {
      _refreshController?.refreshCompleted(resetFooterState: true);
    }
  }

  _loadFail(int page, e) {
    Utils.showTextSnack(context, "加载失败！请重试! ${e.toString()}");
    if (page > 0) {
      _refreshController?.loadFailed();
    }
    setState(() {
      _loadState = StateLayout.stateError;
    });
  }
}
